<template>
  <div class="exhibition-highlights">
    <div
      class="page-header image"
      :style="bannerImage ? { backgroundImage: `url(${bannerImage})` } : {}"
    >
      <div class="header-overlay">
        <div class="container">
          <h1 class="page-title">展会集锦</h1>
          <p class="page-subtitle">回顾FAIR plus机器人全产业链接会的精彩瞬间</p>
        </div>
      </div>
    </div>

    <!-- 导航菜单 -->
    <div class="nav-menu">
      <div class="container">
        <nav class="about-nav">
          <a
            @click="setActiveTab('exhibition-intro')"
            :class="['nav-item', { active: activeTab === 'exhibition-intro' }]"
          >
            展会介绍
          </a>
          <a
            @click="setActiveTab('product-scope')"
            :class="['nav-item', { active: activeTab === 'product-scope' }]"
          >
            展品范围
          </a>
          <a
            @click="setActiveTab('exhibition-highlights')"
            :class="[
              'nav-item',
              { active: activeTab === 'exhibition-highlights' },
            ]"
          >
            展会集锦
          </a>
          <a
            @click="setActiveTab('venue-intro')"
            :class="['nav-item', { active: activeTab === 'venue-intro' }]"
          >
            展馆介绍
          </a>
          <a
            @click="setActiveTab('organizer-intro')"
            :class="['nav-item', { active: activeTab === 'organizer-intro' }]"
          >
            主办方介绍
          </a>
          <a
            @click="setActiveTab('organization-structure')"
            :class="[
              'nav-item',
              { active: activeTab === 'organization-structure' },
            ]"
          >
            组织架构
          </a>
          <a
            @click="setActiveTab('past-exhibitions')"
            :class="['nav-item', { active: activeTab === 'past-exhibitions' }]"
          >
            往届展会
          </a>
          <a
            @click="setActiveTab('downloads')"
            :class="['nav-item', { active: activeTab === 'downloads' }]"
          >
            下载中心
          </a>
        </nav>
      </div>
    </div>

    <div class="container">
      <section class="highlights-section" v-if="exhibitionHighlights.length">
        <div class="highlights-content">
          <el-timeline>
            <el-timeline-item
              v-for="exhibition in exhibitionHighlights"
              :key="exhibition.id"
              placement="top"
              :timestamp="exhibition.title"
              color="var(--e-global-color-title)"
            >
              <el-card>
                <div>
                  <p class="img-b">
                    <img
                      class="img"
                      :src="exhibition.image"
                      :alt="exhibition.title"
                    />
                  </p>
                  <div v-if="exhibition.linkUrl" class="highlight-link">
                    <a
                      :href="exhibition.linkUrl"
                      target="_blank"
                      class="link-button"
                      >查看详情 →</a
                    >
                  </div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
          <!-- 头图+文本（第一条） -->
          <!-- <div v-if="primaryHighlight" class="highlight-item primary">
            <div
              class="highlight-image"
              :class="{ 'full-image': !hasDesc(primaryHighlight) }"
              v-if="primaryHighlight.image"
            >
              <el-image
                :src="primaryHighlight.image"
                :alt="primaryHighlight.title || '展会集锦'"
                :preview-src-list="previewSrcList"
                :initial-index="0"
                fit="contain"
                :z-index="3000"
                preview-teleported
              />
              <div class="highlight-category" v-if="primaryHighlight.category">
                {{ primaryHighlight.category }}
              </div>
            </div>
            <div class="highlight-content" v-if="hasDesc(primaryHighlight)">
              <h3>{{ primaryHighlight.title }}</h3>
              <div
                v-html="primaryHighlight.description"
                class="highlight-description"
              ></div>
              <div
                class="highlight-meta"
                v-if="primaryHighlight.date || primaryHighlight.location"
              >
                <span v-if="primaryHighlight.date">{{
                  primaryHighlight.date
                }}</span>
                <span v-if="primaryHighlight.location">{{
                  primaryHighlight.location
                }}</span>
              </div>
              <div v-if="primaryHighlight.linkUrl" class="highlight-link">
                <a
                  :href="primaryHighlight.linkUrl"
                  target="_blank"
                  class="link-button"
                  >查看详情 →</a
                >
              </div>
            </div>
          </div> -->

          <!-- 缩略图滑动区（其余） -->
          <!-- <div v-if="thumbGroups.length > 0" class="highlights-thumbs">
            <el-carousel
              height="160px"
              arrow="always"
              indicator-position="outside"
            >
              <el-carousel-item v-for="(group, gi) in thumbGroups" :key="gi">
                <div class="thumbs-grid">
                  <div
                    class="thumb-item"
                    v-for="(it, idx) in group"
                    :key="it.id || idx"
                  >
                    <el-image
                      v-if="it.image"
                      :src="it.image"
                      :preview-src-list="previewSrcList"
                      :initial-index="getPreviewIndex(it)"
                      fit="cover"
                      :z-index="3000"
                      preview-teleported
                    >
                      <template #error>
                        <div class="thumb-fallback">无图</div>
                      </template>
                    </el-image>
                  </div>
                </div>
              </el-carousel-item>
            </el-carousel>
          </div> -->
        </div>
      </section>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from "vue";
import { subpageApi } from "@/api/user";
import { selectLangField } from "@/utils/lang";

export default {
  name: "ExhibitionHighlights",
  setup() {
    const activeTab = ref("exhibition-highlights");
    const exhibitionHighlights = ref([]);
    const bannerImage = ref("");
    const hasDesc = (h) =>
      !!(h && typeof h.description === "string" && h.description.trim());
    const primaryHighlight = computed(() =>
      exhibitionHighlights.value && exhibitionHighlights.value.length
        ? exhibitionHighlights.value[0]
        : null
    );
    const others = computed(() => (exhibitionHighlights.value || []).slice(1));
    const chunk = (arr, size) => {
      const res = [];
      for (let i = 0; i < arr.length; i += size)
        res.push(arr.slice(i, i + size));
      return res;
    };
    const thumbGroups = computed(() => {
      const windowWidth = window.innerWidth;
      if (windowWidth > 768) {
        return chunk(others.value, 8);
      } else {
        return chunk(others.value, 3);
      }
    });
    const previewSrcList = computed(() =>
      (exhibitionHighlights.value || [])
        .filter((i) => !!i.image)
        .map((i) => i.image)
    );
    const getPreviewIndex = (item) => {
      const list = previewSrcList.value;
      const idx = list.findIndex((u) => u === item.image);
      return idx >= 0 ? idx : 0;
    };

    const loadData = async () => {
      try {
        const response = await subpageApi.getSubpageByKey(
          "about",
          "exhibition-highlights"
        );
        if (response?.code === "200" && response.data) {
          try {
            // 尝试解析JSON内容
            if (response.data.content) {
              const contentStr = response.data.content.trim();

              // 处理JSON数组格式
              if (contentStr.startsWith("[")) {
                const content = JSON.parse(contentStr);
                if (Array.isArray(content)) {
                  exhibitionHighlights.value = content.map((item) => ({
                    ...item,
                    linkUrl: item.linkUrl || item.link_url || "",
                  }));
                  // 不提前return，继续尝试列表接口以覆盖为真实多条
                }
              }

              // 处理JSON对象格式（单个对象或多个对象）
              if (
                contentStr.startsWith("{") &&
                exhibitionHighlights.value.length === 0
              ) {
                try {
                  // 尝试解析为单个JSON对象
                  const singleObj = JSON.parse(contentStr);
                  if (singleObj.content) {
                    exhibitionHighlights.value = [
                      {
                        id: 1,
                        title: singleObj.subtitle || "展会集锦",
                        description: singleObj.content,
                        image:
                          singleObj.backgroundImage ||
                          response.data.imageUrl ||
                          "",
                        date: new Date().toISOString().split("T")[0],
                        location: "深圳会展中心",
                        category: "展会集锦",
                        linkUrl: singleObj.linkUrl || singleObj.link_url || "",
                      },
                    ];
                  }
                } catch (e) {
                  // 如果不是单个对象，尝试处理多个对象（用换行分隔）
                  const lines = contentStr
                    .split("\n")
                    .filter((line) => line.trim());
                  const highlights = [];
                  lines.forEach((line, index) => {
                    try {
                      const obj = JSON.parse(line.trim());
                      if (obj.content) {
                        highlights.push({
                          id: index + 1,
                          title: obj.subtitle || `展会集锦 ${index + 1}`,
                          description: obj.content,
                          image:
                            obj.backgroundImage || response.data.imageUrl || "",
                          date: new Date().toISOString().split("T")[0],
                          location: "深圳会展中心",
                          category: "展会集锦",
                          linkUrl: obj.linkUrl || obj.link_url || "",
                        });
                      }
                    } catch (parseError) {
                      console.warn("解析JSON行失败:", parseError);
                    }
                  });
                  if (highlights.length > 0) {
                    exhibitionHighlights.value = highlights;
                  }
                }
              }

              // 如果不是JSON格式，尝试解析纯文本内容（仅在尚未填充时）
              if (exhibitionHighlights.value.length === 0) {
                const parsedHighlights = parseTextToHighlights(
                  contentStr,
                  response.data.imageUrl
                );
                if (parsedHighlights.length > 0) {
                  exhibitionHighlights.value = parsedHighlights;
                }
              }
            }
          } catch (e) {
            console.error("解析展会集锦数据失败:", e);
          }
        }

        // 读取多条数据的真实列表，覆盖上面结果
        const listRes = await subpageApi.getSubpageList(
          "about",
          "exhibition-highlights"
        );
        if (
          listRes &&
          listRes.code === "200" &&
          Array.isArray(listRes.data) &&
          listRes.data.length
        ) {
          exhibitionHighlights.value = listRes.data.map((it, idx) => {
            let parsed = {};
            try {
              parsed = it.content
                ? typeof it.content === "string"
                  ? JSON.parse(it.content)
                  : it.content
                : {};
            } catch {}
            return {
              id: it.id || idx + 1,
              title: selectLangField(
                parsed,
                "subtitle",
                selectLangField(
                  it,
                  "title",
                  parsed.subtitle || it.title || "展会集锦"
                )
              ),
              description: selectLangField(parsed, "content", it.content || ""),
              image: selectLangField(
                parsed,
                "backgroundImage",
                it.imageUrl || ""
              ),
              date: parsed.date || "",
              location: parsed.location || "",
              category: parsed.category || "展会集锦",
              linkUrl: it.linkUrl || parsed.linkUrl || parsed.link_url || "",
            };
          });
          console.log(exhibitionHighlights.value);
        }

        if (exhibitionHighlights.value.length === 0) {
          setDefaultData();
        }
      } catch (error) {
        console.error("加载展会集锦数据失败:", error);
        setDefaultData();
      }
    };

    const loadBanner = async () => {
      try {
        const resp = await subpageApi.getContentByType("carousel_about");
        if (
          resp &&
          resp.code === "200" &&
          Array.isArray(resp.data) &&
          resp.data.length
        ) {
          const first =
            resp.data.find((it) => it.status === "active") || resp.data[0];
          const content =
            typeof first.content === "string"
              ? JSON.parse(first.content || "{}")
              : first.content || {};
          bannerImage.value = first.imageUrl || content.image || "";
        }
      } catch (e) {
        bannerImage.value = "";
      }
    };

    // 将纯文本内容转换为展会集锦数据
    const parseTextToHighlights = (textContent, imageUrl) => {
      if (!textContent) return [];

      try {
        // 按行分割内容
        const lines = textContent.split("\n").filter((line) => line.trim());
        const highlights = [];

        lines.forEach((line, index) => {
          if (line.trim()) {
            // 尝试从行中提取信息
            const highlight = {
              id: index + 1,
              title: line.trim(),
              description: line.trim(),
              image:
                imageUrl ||
                `https://images.pexels.com/photos/3861972/pexels-photo-3861972.jpeg?auto=compress&cs=tinysrgb&w=500&h=400&fit=crop&crop=center`,
              date: new Date().toISOString().split("T")[0],
              location: "深圳会展中心",
              category: "展会集锦",
              linkUrl: "",
            };
            highlights.push(highlight);
          }
        });

        return highlights;
      } catch (e) {
        console.error("解析文本到展会集锦失败:", e);
        return [];
      }
    };

    const setDefaultData = () => {
      exhibitionHighlights.value = [
        {
          id: 1,
          title: "FAIR plus 2024盛况回顾",
          description:
            "2024年展会取得了巨大成功，吸引了来自全球的500+展商和50,000+专业观众。",
          image:
            "https://images.pexels.com/photos/3861972/pexels-photo-3861972.jpeg?auto=compress&cs=tinysrgb&w=500&h=400&fit=crop&crop=center",
          date: "2024-05-15",
          location: "深圳会展中心",
          category: "展会回顾",
          linkUrl: "https://example.com/highlight1",
        },
        {
          id: 2,
          title: "FAIR plus 2023精彩瞬间",
          description:
            "2023年展会聚焦智能制造和数字化转型，展示了最新的机器人技术和应用。",
          image:
            "https://images.pexels.com/photos/3861972/pexels-photo-3861972.jpeg?auto=compress&cs=tinysrgb&w=500&h=400&fit=crop&crop=center",
          date: "2023-05-10",
          location: "深圳会展中心",
          category: "展会集锦",
          linkUrl: "https://example.com/highlight2",
        },
      ];
    };

    const setActiveTab = (tabKey) => {
      if (!tabKey) return;
      activeTab.value = tabKey;
      // 跳转到对应的子页面
      if (tabKey !== "exhibition-highlights") {
        window.location.href = `/${tabKey}`;
      }
    };

    onMounted(() => {
      loadData();
      loadBanner();
    });

    return {
      activeTab,
      bannerImage,
      exhibitionHighlights,
      hasDesc,
      primaryHighlight,
      thumbGroups,
      previewSrcList,
      getPreviewIndex,
      setActiveTab,
    };
  },
};
</script>

<style scoped>
.exhibition-highlights {
  background: #f8f9fa;
  min-height: 100vh;
  /* padding-top: 70px; */
}

.page-header {
  background: linear-gradient(135deg, #320063 0%, #4a0a8a 100%);
  color: white;
  padding: 80px 0;
  text-align: center;
}

.page-header.image {
  position: relative;
  background: none;
  padding: 0;
  height: 400px;
  background-size: cover;
  background-position: center;
}
.header-overlay {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.35);
  display: flex;
  align-items: center;
}

.page-title {
  font-size: 48px;
  margin-bottom: 20px;
}

.page-subtitle {
  font-size: 18px;
  opacity: 0.9;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.highlights-section {
  margin: 40px 0;
}

.highlights-content {
  max-width: 1200px;
  margin: 0 auto;
}

.highlight-item {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.highlight-item:hover {
  transform: translateY(-5px);
}

.highlight-image {
  position: relative;
  height: 320px;
  overflow: hidden;
}

.highlight-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}
.highlight-image.full-image {
  height: 420px;
}
.highlight-item.primary .highlight-image {
  height: 440px;
}

.highlight-item:hover .highlight-image img {
  transform: scale(1.05);
}

.highlight-category {
  position: absolute;
  top: 15px;
  right: 15px;
  background: rgba(102, 126, 234, 0.9);
  color: white;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 500;
}

.highlight-content {
  padding: 25px;
}

.highlight-content h3 {
  font-size: 1.4rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
}

.highlight-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 20px;
}

.highlight-description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 20px;
}

.highlight-description p {
  margin-bottom: 12px;
}

.highlight-description ul,
.highlight-description ol {
  margin: 12px 0;
  padding-left: 20px;
}

.highlight-description li {
  margin-bottom: 6px;
}

.highlight-description h1,
.highlight-description h2,
.highlight-description h3,
.highlight-description h4,
.highlight-description h5,
.highlight-description h6 {
  margin: 16px 0 8px 0;
  color: #333;
  font-weight: 600;
}

.highlight-description img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 8px 0;
}

/* 富文本内图片限制 */
.highlight-description :deep(img) {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 10px 0;
  border-radius: 8px;
}

.highlight-meta {
  display: flex;
  gap: 20px;
  color: var(--e-global-color-selected);
  font-size: 0.9rem;
  font-weight: 500;
  margin-bottom: 15px;
}

.highlight-link {
  margin-top: 15px;
}

.link-button {
  display: inline-block;
  background: linear-gradient(
    135deg,
    var(--e-global-color-a3699a4) 0%,
    var(--e-global-color-5c1ca3d) 100%
  );
  color: white;
  padding: 10px 20px;
  border-radius: 25px;
  text-decoration: none;
  font-size: 0.9rem;
  font-weight: 500;
  transition: all 0.3s ease;
  border: none;
  cursor: pointer;
}

.link-button:hover {
  background: linear-gradient(
    135deg,
    var(--e-global-color-5c1ca3d) 0%,
    var(--e-global-color-a3699a4) 100%
  );
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  color: white;
  text-decoration: none;
}

/* 底部缩略图轮播区域，样式与 About.vue 保持一致并略大 */
.highlights-thumbs {
  margin-top: 20px;
  width: 100%;
  padding: 0;
}
.highlights-thumbs :deep(.el-carousel) {
  width: 100%;
}
.highlights-thumbs :deep(.el-carousel__container) {
  width: 100%;
  padding: 0 56px;
}
.highlights-thumbs :deep(.el-carousel__item) {
  display: flex;
  width: 100%;
}
.thumbs-grid {
  width: 100%;
  margin: 0;
  padding: 0;
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 12px;
  @media (max-width: 768px) {
    grid-template-columns: repeat(3, 1fr);
  }
}
.thumb-item :deep(img),
.thumb-item .el-image__inner {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 6px;
}
.thumb-fallback {
  width: 100%;
  height: 150px;
  background: #f0f0f0;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
}

/* 让轮播左右切换按钮更明显 */
:deep(.el-carousel__arrow) {
  width: 44px;
  height: 44px;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  border: 2px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
  transform: translateY(-50%);
}
:deep(.el-carousel__arrow:hover) {
  background-color: rgba(102, 126, 234, 0.9);
  border-color: #fff;
}
:deep(.el-carousel__arrow i) {
  font-size: 18px;
}

@media (max-width: 768px) {
  .page-title {
    font-size: 2rem;
  }

  .highlights-content {
    padding: 0 10px;
  }
}

/* 导航菜单样式 - 参考关于我们页面 */
.nav-menu {
  background: #f8f9fa;
  padding: 20px 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.about-nav {
  display: flex;
  justify-content: center;
  gap: 30px;
  flex-wrap: wrap;
}

.nav-item {
  text-decoration: none;
  color: #333;
  font-size: 1.1rem;
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 8px;
  transition: background-color 0.3s ease, color 0.3s ease;
  border: 1px solid #eee;
  cursor: pointer;
}

.nav-item:hover {
  background-color: var(--e-global-color-selected);
  color: white;
  border-color: var(--e-global-color-selected);
}

.nav-item.active {
  background-color: var(--e-global-color-selected);
  color: white;
  border-color: var(--e-global-color-selected);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .about-nav {
    gap: 15px;
  }

  .nav-item {
    font-size: 1rem;
    padding: 8px 16px;
  }
}

:deep(.el-timeline-item__timestamp) {
  font-size: 20px !important;
  margin-bottom: 20px;
}
.img-b {
  position: relative;
  width: 100%;
  padding-bottom: 60%;
}
.img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.tech-section p {
  color: #666;
  line-height: 1.6;
  font-size: 1rem;
  margin-bottom: 1rem;
}
</style>
